package com.scx.utils;


import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class MongoUtil {
	private static MongoDatabase database;
	
	private final static int MONGODB_PORT = 27017;
	// 链接的数据库名
	private final static String MONGODB_DATABASE = "qiaohaoba";
	// 账号
	private final static String MONGODB_USERNAME = "qhbadmin";
	// 密码
	private final static String MONGODB_PASSWORD = "zQ556677";
	// 每个主机的连接数
	private final static int MONGODB_CONNECTIONS_PRT_HOST = 40;
	// 链接的线程队列数
	private final static int MONGODB_THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER = 3000;
	// 最大等待时长
	private final static int MONGODB_MAX_WAIT_TIME = 5000;
	// 连接超时
	private final static int MONGODB_CONNECT_TIME_OUT = 15000;
	// socket超时0表示无限
	private final static int MONGODB_SOCKET_TIME_OUT = 0;
	
	private static void init() {
		if (null == database) {
			MongoClientOptions options = new MongoClientOptions.Builder()
					.connectionsPerHost(MONGODB_CONNECTIONS_PRT_HOST)
					.connectTimeout(MONGODB_CONNECT_TIME_OUT)
					.maxWaitTime(MONGODB_MAX_WAIT_TIME)
					.socketTimeout(MONGODB_SOCKET_TIME_OUT)
					.threadsAllowedToBlockForConnectionMultiplier(
							MONGODB_THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER)
					.writeConcern(WriteConcern.JOURNALED).build();// 写入方式
			List<ServerAddress> seeds = new ArrayList<ServerAddress>();
//			ServerAddress serverAddress2 = new ServerAddress("192.168.20.6", MONGODB_PORT);
//			ServerAddress serverAddress1 = new ServerAddress("192.168.20.5", MONGODB_PORT);
//			ServerAddress serverAddress3 = new ServerAddress("192.168.20.7", MONGODB_PORT);
//			seeds.add(serverAddress1);
//			seeds.add(serverAddress2);
//			seeds.add(serverAddress3);
//			MongoCredential credentials = MongoCredential.createScramSha1Credential(MONGODB_USERNAME,"admin", MONGODB_PASSWORD.toCharArray());
//			List<MongoCredential> credentialsList = new ArrayList<MongoCredential>();
//			credentialsList.add(credentials);
//			database = new MongoClient(seeds, credentialsList, options).getDatabase(MONGODB_DATABASE);
		}
	}


	/**
	 * 获取collection对象
	 * <p>
	 * </p>
	 * 
	 * @param collName
	 *            Collection名
	 * @return 链接对象
	 */
	public static MongoCollection<Document> getCollection(String collName) {
		init();
		return database.getCollection(collName);
	}
} 